﻿/* 
 * Since 2008 - 2012
 */
package com.hh.bss.mobile.controller;

import static com.hh.bss.util.extjs.JsonHelper.outJson;
import static com.hh.bss.util.extjs.JsonHelper.outJsonArray;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.filters.MappingPropertyFilter;
import net.sf.json.util.PropertyFilter;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;

import com.google.code.kaptcha.Constants;
import com.hh.bss.auth.client.OnlineManager;
import com.hh.bss.auth.client.OnlineUser;
import com.hh.bss.auth.dao.*;
import com.hh.bss.auth.entity.*;
import com.hh.bss.auth.service.*;
import com.hh.bss.auth.vo.query.*;
import com.hh.bss.base.*;
import com.hh.bss.common.cache.SystemRoleResourceCache;
import com.hh.bss.common.cache.SystemUserCache;
import com.hh.bss.common.exception.SystemException;
import com.hh.bss.common.page.*;
import com.hh.bss.common.page.impl.*;
import com.hh.bss.config.Environment;
import com.hh.bss.customer.entity.Company;
import com.hh.bss.project.entity.ContractJobCvCrm;
import com.hh.bss.project.vo.query.ContractJobCvCrmQuery;
import com.hh.bss.sysadmin.entity.SystemDic;
import com.hh.bss.util.*;
import com.hh.bss.util.extjs.ExtJsPageHelper;
import com.hh.bss.util.extjs.JsonHelper;
import com.hh.bss.util.extjs.ListRange;

import java.util.*;




@Controller
public class LoginController extends BaseSpringController {
	// 默认多列排序,example: username desc,createTime asc
	protected static final String DEFAULT_SORT_COLUMNS = null;

	private SystemUserService systemUserService;

	private SystemUser systemUser;
	java.lang.Integer id = null;
	private String[] items;

	/** 通过spring自动注入 */
	public void setSystemUserServiceImpl(SystemUserService service) {
		this.systemUserService = service;
	}

	public void setId(java.lang.Integer val) {
		this.id = val;
	}

	public void setItems(String[] items) {
		this.items = items;
	}

	

	public ModelAndView userlogout(HttpServletRequest request, HttpServletResponse response) {
		OnlineManager onlineManager = new OnlineManager(request, response);
		onlineManager.signOut();
		ModelAndView mav = new ModelAndView("redirect:/mobile/");
		return mav;

	}

	public void userlogin(HttpServletRequest request, HttpServletResponse response) {
		MappingJacksonJsonView view = new MappingJacksonJsonView();
		// view.setContentType("text/html");
		view.setContentType("application/json");
		String inputCode = request.getParameter("randomCode");
		String realCode = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String save_login = request.getParameter("save_login");
		String ip = request.getRemoteAddr(); // 客户端IP
		String pageURI = request.getRequestURI().replaceFirst(request.getContextPath(), "");
		ModelAndView mav = null;
		Map<String, Object> result = new HashMap<String, Object>();

		
		// 参数错用户名或密码为空
		if (StringHelper.isEmpty(password) || StringHelper.isEmpty(username)) {

			result.put("success", false);
			result.put("msg", "登录失败，请确认是否输入正确的用户名和密码");
			outJson(response, result);
			return;

		}

		SystemUser systemUser = systemUserService.findByUsername(username);
		// 用户不存在或密码错误
		String md5passwd = MD5Helper.encode(password + Environment.PASSWORD_MD5_KEY);
		if (systemUser == null || !md5passwd.equals(systemUser.getPasswd())) {
			result.put("success", false);
			result.put("msg", "登录失败，请确认是否输入正确的用户名和密码");
			outJson(response, result);
			return;
		}

		if (!SystemUser.USER_STATUS_NORMAL.equals(systemUser.getStatus())) {
			result.put("success", false);
			result.put("msg", "当前用户已被锁定,请联系管理员解锁");
			outJson(response, result);
			return;
		}
		// 设置cookie

		OnlineManager onlineManager = new OnlineManager(request, response);
		OnlineUser onlineUser = new OnlineUser();
		onlineUser.setId(systemUser.getId());
		onlineUser.setUsername(systemUser.getAccount());
		onlineUser.setType(0);
		onlineUser.setHistoryId(systemUser.getId());
		onlineUser.setSignInTime(new Date());
		onlineUser.setName(systemUser.getName());
		Map m = SystemUserCache.getUserRoles(systemUser.getId());
		// m.keySet()
		if (m != null) {
			StringBuffer sb = new StringBuffer();
			for (Iterator it = m.keySet().iterator(); it.hasNext();) {
				if (sb.length() > 0)
					sb.append(",").append(it.next());
				else
					sb.append(it.next());
			}
			onlineUser.setRoleIds(sb.toString());
		}
		onlineManager.signIn(onlineUser);

		try {
			onlineManager.addCookie("name", URLEncoder.encode(systemUser.getName(), "utf-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		onlineManager.addCookie("username", systemUser.getAccount());
		onlineManager.addCookie("id", systemUser.getId().toString());
		if (StringUtils.isNotEmpty(save_login) && "1".equals(save_login)) {
			onlineManager.addCookie("password", password);
			logger.info("U/P:" + username + "=" + password);
		} else {
			onlineManager.removeCookie("password");
		}

		System.out.println(onlineUser.getRoleIds());
		if (!StringHelper.isEmpty(onlineUser.getRoleIds()))
			onlineManager.addCookie("role", onlineUser.getRoleIds());

		/*
		// 验证Ip 和权限
		if (!this.systemUserService.validateIP(ip)) {
			if (!onlineManager.hasPermission(pageURI,onlineUser)) {
				result.put("success", false);
				result.put("msg", "登录失败,由于您不是在办公室登陆,IP受限,请联系管理员取得相应的授权.");
				outJson(response, result);
				return;
			}

		}
		*/
		result.put("success", true);
		result.put("msg", "成功!");
		outJson(response, result);

	}

	

}
